package com.andnnl.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 把proxool.xml 按数据源名称排序
 * Created by chenss on 2023/9/18.
 */
public class ProxoolXmlSort {
    public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, TransformerException {
        File xmlFile = new File("src/main/resources/proxool.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();

        // 获取所有proxool元素
        NodeList proxoolList = doc.getElementsByTagName("proxool");
        List<Element> proxools = new ArrayList<>();
        for (int i = 0; i < proxoolList.getLength(); i++) {
            proxools.add((Element) proxoolList.item(i));
        }

        // 根据alias排序
        Collections.sort(proxools, new Comparator<Element>() {
            @Override
            public int compare(Element e1, Element e2) {
                String alias1 = e1.getElementsByTagName("alias").item(0).getTextContent();
                String alias2 = e2.getElementsByTagName("alias").item(0).getTextContent();
                System.out.println(alias1);
                System.out.println(alias2);
                System.out.println(alias1.compareTo(alias2));
                if (alias1.equals("ch_emas_sms")) return 1; //排到最后面
                if (alias2.equals("ch_emas_sms")) return -1; //排到最后面
                return alias1.compareTo(alias2);
            }
        });

        // 打印排序后的结果
        for (Element proxool : proxools) {
            System.out.println(proxool.getElementsByTagName("alias").item(0).getTextContent());
            // 可以在这里处理每个proxool元素的其他属性或子元素
        }

        saveToXml(proxools);
    }

    private static void saveToXml(List<Element> proxools) throws ParserConfigurationException, TransformerException {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.newDocument();

// 创建proxool-config元素作为根元素
        Element proxoolConfig = doc.createElement("proxool-config");
        doc.appendChild(proxoolConfig);

// 将排序后的proxool元素添加到proxool-config元素中
        for (Element proxool : proxools) {
            Node newNode = doc.importNode(proxool, true); // 复制节点到doc2
            proxoolConfig.appendChild(newNode);
        }

// 创建TransformerFactory和Transformer实例
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        doc.setXmlStandalone(true);
// 创建DOMSource和StreamResult实例，并将它们传递给Transformer的transform方法
        DOMSource source = new DOMSource(doc);
        System.out.println(source.toString());
        StreamResult result = new StreamResult(new File("src/main/resources/proxool2.xml"));
        transformer.transform(source, result);


        // 创建一个StreamResult对象，用于将XML字符串写入到byte数组中
        StreamResult result2 = new StreamResult(new ByteArrayOutputStream());
// 使用Transformer将Source转换为Result
        transformer.transform(source, result2);

// 获取byte数组并创建InputStream
        byte[] xmlBytes = ((ByteArrayOutputStream) result2.getOutputStream()).toByteArray();
//        InputStream inputStream = new ByteArrayInputStream(xmlBytes);
        System.out.println(new String(xmlBytes));
    }
}
